<?php
declare (strict_types=1);

namespace app\course\service\live\admin;

use app\common\service\BaseService;
use app\course\logic\base\Course;
use app\course\logic\live\admin\LiveSmallSection as SectionLogic;
use app\course\model\live\CourseSectionLive as LiveData;
use eduline\admin\libs\pageform\FormItem;
use eduline\admin\libs\pagelist\ListItem;
use eduline\admin\page\PageForm;
use eduline\admin\page\PageList;
use think\annotation\Inject;
use think\facade\Request;

/**
 * 直播课程课时接口类-后台
 */
class LiveSmallSection extends BaseService
{
    /**
     * @Inject()
     * @var SectionLogic
     */
    protected $secLogic;

    /**
     * 课时列表
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-04-28
     *
     * @param int $id [description]
     * @return   [type]                             [description]
     */
    public function sectionTree(int $id)
    {
        $data = $this->secLogic->sectionTree($id);
        // 定义字段
        $keyList = [
            'title' => ListItem::make()->title('名称'),
            'price' => ListItem::make('custom')->title('价格(单位:元)'),
            'simple_time'  => ListItem::make()->title('开课时间'),
            'live'  => ListItem::make('custom')->title('开课状态'),
        ];
        // 设置表单
        $list = app(PageList::class);
        // 表单字段
        $list->pageKey = $keyList;
        $list->datas   = $data;

        // 课程信息
        // 是否已经完结
        $list->is_finished = app(\app\course\logic\base\admin\Course::class)->isFinished($id);

        return $list->send();
    }

    /**
     * 分类子集
     * Author   亓官雨树<lucky.max@foxmail.com>
     * Date 2020-03-28
     */
    public function getChildren(int $id, int $pid)
    {
        $data = $this->secLogic->sectionTree($id, $pid);
        return $this->parseToData($data, 1, '获取成功');
    }

    /**
     * 创建课时
     * Author   亓官雨树<lucky.max@foxmail.com>
     * Date 2020-03-30
     */
    public function addSection(int $id = 0, int $pid = 0)
    {
        if (Request::isPost()) {
            $data = Request::post();
            $re   = $this->secLogic->addSection($id, $pid, $data);
            // return $this->parseToData($re, 1, 'test');
            return $this->parseToData($re->toArray(), 1, '添加成功');
        }

        /* 创建课程界面配置 */
        $keyList = [
            'title' => FormItem::make()->title('课时名称')->required(),
        ];
        // 最后一个课时允许添加课件与价格
        if ($this->secLogic->isLastSction($id, $pid)) {
            // $keyList['price']      = FormItem::make('inputNumber')->title('课时价格')->min(0)->precision(2);
            $keyList['time']       = FormItem::make('custom')->title('开课时间')->required();
            $keyList['class_hour'] = FormItem::make('inputNumber')->title('学时')->min(0);
            // $keyList['course_ids'] = FormItem::make('custom')->title('直播带课');
        }
        // 设置表单
        $form = app(PageForm::class);
        // 表单字段
        $form->pageKey = $keyList;
        // 排序
        // $form->pageKeySort = ['mhm_id'];
        $form->saveMethod  = 'POST';
        $url               = '/course/admin/live/small/' . $id . '/section/' . $pid;
        $form->savePostUrl = $url;

        return $form->send();
    }

    /**
     * 修改课时界面
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-04-27
     *
     * @param int $sid [description]
     * @param int $id  [description]
     * @return   [type]                              [description]
     */
    public function update(int $id, int $sid)
    {
        if (Request::isPut()) {
            $data    = Request::put();
            $section = SectionLogic::findOrFail($sid);
            $section = $this->secLogic->editSection($section, $data);

            return $this->parseToData($section, 1, '编辑成功');
        }

        $data = $this->secLogic->where('id', $sid)->findOrFail();

        if ($data->course_ids) {
            $course_ids = explode(',', trim($data->course_ids, ','));
            foreach ($course_ids as &$course_id) {
                $course_id += 0;
            }
            unset($course_id);
            $data->course_ids = $course_ids;
        } else {
            $data->course_ids = [];
        }

        $data->course_ids = app(Course::class)
            ->where('id', 'IN', $data->course_ids)
            ->field('id,title,cover')
            ->with(['cover_url'])
            ->select();

        // 查询课时关联数据
        if ($data->live_provider !== 3) {
            // 非CC云课堂直播
            $live_data                = app(LiveData::class)->where('room_no', $sid)->findOrEmpty();
            $data->playback_id_attach = $live_data;
            $data->playback_id        = $live_data->attach_id;

            $time         = time();
            $data->is_end = (int)($data->end_time < $time || (!$live_data->isEmpty() && $live_data->close_time < $time));
        } else {
            // CC云课堂直播
            $live_data           = app(LiveData::class)->where('room_no', $sid)->findOrEmpty();
            $data->cc_replay_url = $live_data->cc_replay_url;

            $time         = time();
            $data->is_end = (int)($data->end_time < $time || !$live_data->isEmpty());
        }

        $timeKeyList = $data->is_end ? "word" : "custom";

        /* 创建课程界面配置 */
        $keyList = [
            'title' => FormItem::make()->title('课时名称')->required()->disabled(!!$data->is_end),
        ];
        if ($this->secLogic->isLastSction($id, $data->pid)) {
            // $keyList['price'] = FormItem::make('inputNumber')->title('课时价格')->min(0)->precision(2)->disabled($data->is_end);
            $keyList['time'] = FormItem::make($timeKeyList)->title('开课时间')->required();

            if ($data->start_time && $data->end_time) {
                if ($data->is_end) {
                    $data->time = date('Y-m-d H:i', $data->start_time) . ' - ' . date('Y-m-d H:i', $data->end_time);
                } else {
                    $data->time = [
                        'date'      => date('Y-m-d', $data->start_time),
                        'time_slot' => [
                            date('H:i', $data->start_time),
                            date('H:i', $data->end_time),
                        ],
                    ];
                }
            }

            $keyList['class_hour'] = FormItem::make('inputNumber')->title('学时')->min(0)->disabled(!!$data->is_end);
            // $keyList['course_ids'] = FormItem::make('custom')->title('直播带课');
            if ($data->is_end) {
                if ($data->live_provider !== 3) {
                    // 只有课时 + 直播服务商不是CC事,才需要上传回放视频
                    $keyList['playback_id'] = FormItem::make('custom')->title('直播回放视频');
                } else {
                    $help                     = '前往 <a href="https://admin.bokecc.com/liveclass/list.bo" target="_blank" class="el-link el-link--primary"> CC - 管理端 </a> 获取';
                    $keyList['cc_replay_url'] = FormItem::make()->title('直播回放视频地址')->help($help);
                }
            }
        }

        // 设置表单
        $form = app(PageForm::class);
        // 表单字段
        $form->pageKey     = $keyList;
        $form->saveMethod  = 'PUT';
        $url               = '/course/admin/live/small/' . $id . '/section/' . $sid;
        $form->savePostUrl = $url;

        $form->datas = $data;

        return $form->send();

    }

    /**
     * 编辑指定的字段
     * Author   亓官雨树<lucky.max@foxmail.com>
     * Date 2020-03-27
     */
    public function updateSort($sid)
    {
        $value = Request::put('best_sort/d');
        $video = $this->secLogic->updateSort($sid, $value);

        return $this->parseToData($video, 1, '编辑成功');
    }

    /**
     * 删除课时
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-04-28
     *
     * @param int $sid [description]
     * @return   [type]                              [description]
     */
    public function delete(int $sid)
    {
        $this->secLogic->sectionDelete($sid);

        return $this->parseToData([], 1, '删除成功');

    }

}
